package com.dg11185.nearshop.baidumap;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.android.nearshop.R;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.dg11185.libs.utils.string.StringUtils;
import com.dg11185.nearshop.app.ConvertUnit;
import com.dg11185.nearshop.app.DataCache;
import com.dg11185.nearshop.baidumap.RouteListAdapter.RouteData;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorListenerAdapter;
import com.nineoldandroids.animation.ObjectAnimator;
import com.umeng.analytics.MobclickAgent;

/**
 * 用户查看路径界面
 * 
 * @author：Daibo
 * @time：2014-7-5 下午12:40:19
 */
public class ChoiceRouteActivity extends Activity implements OnClickListener {

    /** 隐藏加载动画的 msg.what的值 */
    private static final int LOADING_TAG_SUCCESS = 0x00000000;

    private static final int LOADING_TAG_ERROR = 0x00000001;

    private static final int SHORTEST_LOADING_TIME = 200;

    /** 我的位置在上=true, 我的位置在下=false, {@link #exchangeRoute}按钮被点击时改变 ，用来控制动画移动 */
    private boolean IS_ON_INITIAL_STATE = true;

    /**
     * 使用地图定位还是用户自定义 定位=true, 自定义=false; {@link #choiceMyPosition}
     * {@link #choiceOnMap}被点击时改变
     */
    private boolean IS_AUTO_LOCATION_DATA = true;

    /**
     * 用来标记当前{@link #tAdapter} {@link #dAdapter} {@link #wAdapter}
     * 三者的值是否有效，false需要加载路线数据，true不需要重新加载； 当起始位置改变时，数组全部重置为false；
     * {@link #listener}被回调时，修改相应值为true {@link #exchangeDestnation()}
     * {@link #onActivityResult(int, int, Intent)} {@link #choiceOnMap}
     * 这三个方法会修改起始位置，重置数组；
     */
    private boolean[] IS_CONTAINS_VALID_VALUE = new boolean[] { false, false, false };

    // 公交，驾车，步行分别对应 0、1、2
    private int TRAFFIC_STATE = 0;

    /** 主界面控件相关变量 */
    private RelativeLayout fromPoiLayout;// 点击我的位置时响应点击事件

    private RelativeLayout toPoiLayout;// 点击exchange交换layout位置

    private TextView fromPositionTv, toPositionTv;

    private ImageView btnTransit, btnDriving, btnWalking;

    private ListView routeList;

    /** 阴影界面控件相关变量 */
    private RelativeLayout shadowLayout;

    private LinearLayout animLayout; // 用于显示动画的layout

    /***/
    private ProgressBar loadingLayout;

    private LinearLayout wrongLayout;

    /** Intent获取参数，分别表示百度定位坐标、用户选择坐标、商家坐标 */
    private double[] poi_loc, poi_custom, poi_shop;

    private EntityShopData shopData;

    private BDLocation location;

    /** 获取路径的单实例类 */
    private MyMapRoute mapRoute;

    /** {@link SimpleAdapter}使用的数据结构 */
    private List<RouteData> tList = new ArrayList<RouteListAdapter.RouteData>();

    private List<RouteData> dList = new ArrayList<RouteListAdapter.RouteData>();

    private List<RouteData> wList = new ArrayList<RouteListAdapter.RouteData>();

    private RouteListAdapter routeAdapter;

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
            case LOADING_TAG_SUCCESS:
                routeList.setVisibility(View.VISIBLE);
                loadingLayout.setVisibility(View.INVISIBLE);
                wrongLayout.setVisibility(View.INVISIBLE);
                break;

            case LOADING_TAG_ERROR:
                routeList.setVisibility(View.INVISIBLE);
                loadingLayout.setVisibility(View.INVISIBLE);
                wrongLayout.setVisibility(View.VISIBLE);
                break;
            default:
                break;
            }
        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.map_shop_route_choice);

        initIntentData();
        /** 初始化按钮和相关回调事件 */
        fromPoiLayout = (RelativeLayout) this.findViewById(R.id.route_from_layout);
        toPoiLayout = (RelativeLayout) this.findViewById(R.id.route_to_layout);
        fromPositionTv = (TextView) this.findViewById(R.id.route_from_position);
        toPositionTv = (TextView) this.findViewById(R.id.route_to_position);
        toPositionTv.setText(shopData.shopTitle);
        this.findViewById(R.id.route_exchange).setOnClickListener(this);
        btnTransit = (ImageView) this.findViewById(R.id.route_transit_img);
        btnDriving = (ImageView) this.findViewById(R.id.route_drive_img);
        btnWalking = (ImageView) this.findViewById(R.id.route_walk_img);
        routeList = (ListView) this.findViewById(R.id.route_listview);
        routeList.setOnItemClickListener(new ItemClickedListener());
        routeAdapter = new RouteListAdapter(this);
        routeList.setAdapter(routeAdapter);

        loadingLayout = (ProgressBar) this.findViewById(R.id.route_progress_layout);
        wrongLayout = (LinearLayout) this.findViewById(R.id.route_wrong_layout);

        shadowLayout = (RelativeLayout) this.findViewById(R.id.route_shadow_layout);
        animLayout = (LinearLayout) this.findViewById(R.id.route_shadow_data_layout);
        findViewById(R.id.route_choice_my_position).setOnClickListener(this);
        findViewById(R.id.route_choice_on_map).setOnClickListener(this);
        findViewById(R.id.route_choice_cancel).setOnClickListener(this);

        fromPoiLayout.setOnClickListener(this);
        btnTransit.setOnClickListener(this);
        btnDriving.setOnClickListener(this);
        btnWalking.setOnClickListener(this);

        /** 初始化Route类，和它的相关参数 */
        mapRoute = MyMapRoute.getInstance().setCityName(shopData.shopCity).setStNode(poi_loc).setEnNode(poi_shop)
                .setMyListener(listener);
        mapRoute.startTransitSearch();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (shadowLayout.getVisibility() == View.VISIBLE) {
            dismissShadowView();
        }
        MobclickAgent.onPageStart(getClass().getName());
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(getClass().getName());
        MobclickAgent.onPause(this);
    }

    private void initIntentData() {
        /** 获取intent中的数据 */
        shopData = (EntityShopData) DataCache.getValue(MapConstant.dataShopInfoForMap);
        location = MyMapLocation.location;
        poi_shop = new double[] { Double.parseDouble(shopData.shopLatitude), Double.parseDouble(shopData.shopLongitude) };
        if(location == null){
            poi_loc = new double[]{MapConstant.getDefaultPoint().latitude, MapConstant.getDefaultPoint().longitude};
        }else{
            poi_loc = new double[] { location.getLatitude(), location.getLongitude() };
        }
    }

    /**
     * 点击公交、自驾或步行按钮后调用
     * {@link MyMapRoute #startDrivingSearch(RouteSearchListener)} 方法获取数据之后回调
     */
    private RouteSearchListener listener = new RouteSearchListener() {

        @Override
        public void onGetTransitRouteResult(TransitRouteResult arg0) {
            if (arg0 == null || arg0.error != SearchResult.ERRORNO.NO_ERROR
                    || arg0.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
                handler.sendEmptyMessageDelayed(LOADING_TAG_ERROR, SHORTEST_LOADING_TIME);
                return;
            }
            handler.sendEmptyMessageDelayed(LOADING_TAG_SUCCESS, SHORTEST_LOADING_TIME);
            IS_CONTAINS_VALID_VALUE[0] = true;
            tList.clear();
            try {   //路径名百度没有提供明确的API，是通过其它字符串截取的，很可能包含错误。
                for (int a = 0; a < arg0.getRouteLines().size(); a++) {
                    RouteData data = new RouteData();
                    for (int b = 0; b < arg0.getRouteLines().get(a).getAllStep().size(); b++) {
                        String step = arg0.getRouteLines().get(a).getAllStep().get(b).getInstructions();
                        if (step.contains("乘坐")) {
                            int lastIndex = 0;
                            if(step.contains(")")){
                                lastIndex = step.indexOf("),") + 1;
                            }else{
                                lastIndex = step.indexOf(",");
                            }
                            if(lastIndex >2 ){
                                if(StringUtils.isBlank(data.content)){
                                    data.content += step.substring(2, lastIndex);
                                }else{
                                    data.content = data.content + "-" + step.substring(2, lastIndex);
                                }
                            }
                        }
                    }
                    data.numerical = (a + 1) + "";
                    data.distance = ConvertUnit.meter2KiloMeter(arg0.getRouteLines().get(a).getDistance());
                    data.time = ConvertUnit.second2Minute(arg0.getRouteLines().get(a).getDuration());
                    tList.add(data);
                }

                routeAdapter.setRouteList(tList);
                routeAdapter.notifyDataSetChanged();
			} catch (Exception e) {
				e.printStackTrace();
			}

        }

        @Override
        public void onGetDrivingRouteResult(DrivingRouteResult arg0) {
            if (arg0 == null || arg0.error != SearchResult.ERRORNO.NO_ERROR
                    || arg0.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
                handler.sendEmptyMessageDelayed(LOADING_TAG_ERROR, SHORTEST_LOADING_TIME);
                return;
            }
            handler.sendEmptyMessageDelayed(LOADING_TAG_SUCCESS, SHORTEST_LOADING_TIME);
            IS_CONTAINS_VALID_VALUE[1] = true;
            dList.clear();
            int count = 3;
            int temp = 0;
            String content = "途径 ";
            for (int a = 0; a < arg0.getRouteLines().get(0).getAllStep().size(); a++) {
                String c = arg0.getRouteLines().get(0).getAllStep().get(a).getInstructions();

                if (c.contains("进入")) {
                    temp++;
                    if (temp == 1) {
                        content += c.substring(c.indexOf("进入") + 2, c.length());
                    } else {
                        content = content + "、" + c.substring(c.indexOf("进入") + 2, c.length());
                    }
                }
                if (temp >= count) {
                    break;
                }
            }
            RouteData data = new RouteData();
            data.content = content;
            data.distance = ConvertUnit.meter2KiloMeter(arg0.getRouteLines().get(0).getDistance());
            data.time = ConvertUnit.second2Minute(arg0.getRouteLines().get(0).getDuration());
            dList.add(data);

            routeAdapter.setRouteList(dList);
            routeAdapter.notifyDataSetChanged();
        }

        @Override
        public void onGetWalkingRouteResult(WalkingRouteResult arg0) {
            if (arg0 == null || arg0.error != SearchResult.ERRORNO.NO_ERROR
                    || arg0.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
                handler.sendEmptyMessageDelayed(LOADING_TAG_ERROR, SHORTEST_LOADING_TIME);
                return;
            }
            handler.sendEmptyMessageDelayed(LOADING_TAG_SUCCESS, SHORTEST_LOADING_TIME);
            wList.clear();
            IS_CONTAINS_VALID_VALUE[2] = true;
            int count = 3;
            int temp = 0;
            String content = "途径 ";
            for (int a = 0; a < arg0.getRouteLines().get(0).getAllStep().size(); a++) {
                String c = arg0.getRouteLines().get(0).getAllStep().get(a).getInstructions();

                if (c.contains("进入")) {
                    temp++;
                    if (temp == 1) {

                        content += c.substring(c.indexOf("进入") + 2, c.length());
                    } else {
                        content = content + "、" + c.substring(c.indexOf("进入") + 2, c.length());
                    }
                }
                if (temp >= count) {
                    break;
                }
            }
            RouteData data = new RouteData();
            data.content = content;
            data.distance = ConvertUnit.meter2KiloMeter(arg0.getRouteLines().get(0).getDistance());
            data.time = ConvertUnit.second2Minute(arg0.getRouteLines().get(0).getDuration());
            wList.add(data);

            routeAdapter.setRouteList(wList);
            routeAdapter.notifyDataSetChanged();
        }
    };

    /** Adapter的点击事件处理 */
    private class ItemClickedListener implements OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            String content, distance;
            if (TRAFFIC_STATE == 0) {
                content = (String) tList.get(position).content;
                distance = (String) tList.get(position).distance;
            } else if (TRAFFIC_STATE == 1) {
                content = (String) dList.get(position).content;
                distance = (String) dList.get(position).distance;
            } else {
                content = (String) wList.get(position).content;
                distance = (String) wList.get(position).distance;
            }
            Intent intent = new Intent(ChoiceRouteActivity.this, ShopRouteActivity.class);
            intent.putExtra("route_position", position);
            intent.putExtra("traffic_state", TRAFFIC_STATE);
            intent.putExtra("route_content", content);
            intent.putExtra("route_distance", distance);
            startActivity(intent);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.route_from_layout:
            showShadowView();
            break;
        case R.id.route_exchange:
            exchangeDestnation();
            break;
        case R.id.route_transit_img:
            TRAFFIC_STATE = 0;
            if (IS_CONTAINS_VALID_VALUE[0]) {
                routeAdapter.setRouteList(tList);
                routeAdapter.notifyDataSetChanged();
                handler.sendEmptyMessage(LOADING_TAG_SUCCESS);
            } else {
                mapRoute.startTransitSearch();
                setLoadingState();
            }
            btnTransit.setImageResource(R.drawable.map_route_bus_on);
            btnDriving.setImageResource(R.drawable.map_route_drive_off);
            btnWalking.setImageResource(R.drawable.map_route_walk_off);
            break;
        case R.id.route_drive_img:
            TRAFFIC_STATE = 1;
            if (IS_CONTAINS_VALID_VALUE[1]) {
                routeAdapter.setRouteList(dList);
                routeAdapter.notifyDataSetChanged();
                handler.sendEmptyMessage(LOADING_TAG_SUCCESS);
            } else {
                mapRoute.startDrivingSearch();
                setLoadingState();
            }

            btnTransit.setImageResource(R.drawable.map_route_bus_off);
            btnDriving.setImageResource(R.drawable.map_route_drive_on);
            btnWalking.setImageResource(R.drawable.map_route_walk_off);
            break;
        case R.id.route_walk_img:
            TRAFFIC_STATE = 2;
            if (IS_CONTAINS_VALID_VALUE[2]) {
                routeAdapter.setRouteList(wList);
                routeAdapter.notifyDataSetChanged();
                handler.sendEmptyMessage(LOADING_TAG_SUCCESS);
            } else {
                mapRoute.startWalkingSearch();
                setLoadingState();
            }
            btnTransit.setImageResource(R.drawable.map_route_bus_off);
            btnDriving.setImageResource(R.drawable.map_route_drive_off);
            btnWalking.setImageResource(R.drawable.map_route_walk_on);
            break;
        case R.id.route_choice_my_position:
            onChoiceMyPositionClicked();
            break;
        case R.id.route_choice_on_map:
            startActivityForResult(new Intent(this, ChoicePositionActivity.class), 1);
            break;
        case R.id.route_choice_cancel:
            dismissShadowView();
            break;
        default:
            break;
        }
    }

    /**
     * 隐藏弹出面板、修改起始位置文本框数据、重新设置并加载数据
     */
    private void onChoiceMyPositionClicked() {
        dismissShadowView();
        if (IS_AUTO_LOCATION_DATA) {
            return;
        } else {
            fromPositionTv.setText("我的位置");
            if (IS_ON_INITIAL_STATE) {
                mapRoute = mapRoute.setStNode(poi_loc).setEnNode(poi_shop);
            } else {
                mapRoute = mapRoute.setStNode(poi_shop).setEnNode(poi_loc);
            }
            resetAndReloadData();
        }

        IS_AUTO_LOCATION_DATA = true;
    }

    /** 加载动画、重置数组、重新加载路线数据 */
    private void exchangeDestnation() {

        if (IS_ON_INITIAL_STATE) {
            ObjectAnimator.ofFloat(fromPoiLayout, "translationY", 0, fromPoiLayout.getHeight()).setDuration(200)
                    .start();
            ObjectAnimator.ofFloat(toPoiLayout, "translationY", 0, -toPoiLayout.getHeight()).setDuration(200).start();
        } else {
            ObjectAnimator.ofFloat(fromPoiLayout, "translationY", fromPoiLayout.getHeight(), 0).setDuration(200)
                    .start();
            ObjectAnimator.ofFloat(toPoiLayout, "translationY", -toPoiLayout.getHeight(), 0).setDuration(200).start();

        }

        IS_ON_INITIAL_STATE = !IS_ON_INITIAL_STATE;

        if (IS_ON_INITIAL_STATE && IS_AUTO_LOCATION_DATA) {
            mapRoute = mapRoute.setStNode(poi_loc).setEnNode(poi_shop);
        } else if (IS_ON_INITIAL_STATE && !IS_AUTO_LOCATION_DATA) {
            mapRoute = mapRoute.setStNode(poi_custom).setEnNode(poi_shop);
        } else if (!IS_ON_INITIAL_STATE && IS_AUTO_LOCATION_DATA) {
            mapRoute = mapRoute.setStNode(poi_shop).setEnNode(poi_loc);
        } else if (!IS_ON_INITIAL_STATE && !IS_AUTO_LOCATION_DATA) {
            mapRoute = mapRoute.setStNode(poi_shop).setEnNode(poi_custom);
        }
        resetAndReloadData();
    }

    private void showShadowView() {

        shadowLayout.setVisibility(View.VISIBLE);
        ObjectAnimator.ofFloat(shadowLayout, "alpha", 0, 1).setDuration(200).start();
        ObjectAnimator.ofFloat(animLayout, "translationY", animLayout.getHeight(), 0, 30, 0).setDuration(400).start();
    }

    /**
     * 
     * dismissShadowView(这里用一句话描述这个方法的作用)
     * 
     * @param name
     * @param @return 设定文件
     * @return String DOM对象
     * @Exception 异常对象
     */
    private void dismissShadowView() {
        ObjectAnimator oa = ObjectAnimator.ofFloat(shadowLayout, "alpha", 1, 0);
        ObjectAnimator
                .ofFloat(animLayout, "translationY", 0, animLayout.getHeight(), animLayout.getHeight() - 30,
                        animLayout.getHeight()).setDuration(400).start();

        oa.setDuration(500);
        oa.start();
        oa.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                shadowLayout.setVisibility(View.GONE);
            }
        });
    }

    @Override
    /**
     * 从{@link ChoicePositionActivity}类获取用户选择的地理位置
     */
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (resultCode) {
        case RESULT_OK:
            Bundle bundle = data.getExtras();
            if (!bundle.getBoolean("IS_CHOICED", false))
                break;
            String content = bundle.getString("GEO_CONTENT");
            poi_custom = bundle.getDoubleArray("GEO_POINT");
            IS_AUTO_LOCATION_DATA = false;

            fromPositionTv.setText(content);
            if (IS_ON_INITIAL_STATE) {
                mapRoute.setStNode(poi_custom).setEnNode(poi_shop);
            } else {
                mapRoute.setStNode(poi_shop).setEnNode(poi_custom);
            }
            resetAndReloadData();
            break;

        default:
            break;
        }
    }

    private void resetAndReloadData() {
        for (int c = 0; c < IS_CONTAINS_VALID_VALUE.length; c++) {
            IS_CONTAINS_VALID_VALUE[c] = false;
        }
        tList.clear();
        dList.clear();
        wList.clear();
        if (TRAFFIC_STATE == 0) {
            mapRoute.startTransitSearch();
        } else if (TRAFFIC_STATE == 1) {
            mapRoute.startDrivingSearch();
        } else {
            mapRoute.startWalkingSearch();
        }
        setLoadingState();
    }

    private void setLoadingState() {
        loadingLayout.setVisibility(View.VISIBLE);
        routeList.setVisibility(View.INVISIBLE);
        wrongLayout.setVisibility(View.INVISIBLE);
    }

    public void onBackClicked(View v) {
        this.finish();
    }
}
